<?php

namespace Model;

use App\Model;


class WechatSdkModel extends Model
{
    protected $api_host = 'https://api.weixin.qq.com/';

    // hook model_wechatsdk_start.php

    //验证签名
    public function valid($post)
    {
        $token = _CONF('wxgzh_token');
        $echoStr = $post['echostr'];
        $signature = $post['signature'];
        $timestamp = $post['timestamp'];
        $nonce = $post['nonce'];
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);
        if ($tmpStr == $signature) {
            return $echoStr;
        }
    }

    public function get_access_token($reload=0)
    {
        $appid = _CONF('wxgzh_appid');
        if(empty($appid)){
            return false;
        }
        $data =  $this->_T('Config')->get('wx_access_token', 'Value');
        if (!empty($data) && empty($reload)) {
            return $data;
        }
        $url = $this->api_host . 'cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . _CONF('wxgzh_appsecret');
        $json = https_get($url);
        $json = xn_json_decode($json);
        !empty($json['errcode']) and xn_log($json['errcode'], 'wxerror');
        if (!empty($json['access_token'])) {
            $this->_T('Config')->set('wx_access_token', ['Json' => 0, 'Value' => $json['access_token']]);
            return $json['access_token'];
        }
        return false;
    }

    public function JsSdk($url, $debug = false, $beta = false)
    {
        $apiList = ['openAddress', 'updateTimelineShareData', 'updateAppMessageShareData', 'onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareWeibo', 'onMenuShareQZone', 'startRecord', 'stopRecord', 'onVoiceRecordEnd', 'playVoice', 'pauseVoice', 'stopVoice', 'onVoicePlayEnd', 'uploadVoice', 'downloadVoice', 'chooseImage', 'previewImage', 'uploadImage', 'downloadImage', 'translateVoice', 'getNetworkType', 'openLocation', 'getLocation', 'hideOptionMenu', 'showOptionMenu', 'hideMenuItems', 'showMenuItems', 'hideAllNonBaseMenuItem', 'showAllNonBaseMenuItem', 'closeWindow', 'scanQRCode', 'chooseWXPay', 'openProductSpecificView', 'addCard', 'chooseCard', 'openCard'];
        $signPackage = $this->signature($url);
        $base = [
            'debug' => $debug,
            'beta' => $beta,
        ];
        return array_merge($base, $signPackage, ['jsApiList' => $apiList]);
    }

    public function Ticket()
    {
        $key = 'wx:ticket:' . _CONF('wxgzh_appid');
        $ticket = $this->CacheGet($key);
        if (empty($ticket['ticket'])) {
            $access_token = $this->get_access_token();
            $api_ticket = $this->api_host . 'cgi-bin/ticket/getticket';
            $result = https_get($api_ticket . '?access_token=' . $access_token . '&type=jsapi');
            $result = xn_json_decode($result);
            !empty($result['errcode']) and xn_log($result['errmsg'], 'wxerror');
            if (!empty($result['errcode']) && $result['errcode'] == 40001) {
                $this->CacheDel('wx:access');
                return $this->Ticket();
            }
            $ticket = $result['ticket'];
            !empty($result['ticket']) && $this->CacheSet($key, $result, 7000);
        } else {
            $ticket = $ticket['ticket'];
        }
        return $ticket;
    }


    /**
     * Build signature.
     *
     * @param string $url
     * @param string $nonce
     * @param int $timestamp
     *
     * @return array
     */
    public function signature($url, $nonce = null, $timestamp = null)
    {
        $nonce = $nonce ? $nonce : xn_rand(10);
        $timestamp = $timestamp ? $timestamp : time();
        $ticket = $this->Ticket();
        $sign = [
            'appId' => _CONF('wxgzh_appid'),
            'nonceStr' => $nonce,
            'timestamp' => $timestamp,
            'url' => $url,
            'signature' => $this->getSignature($ticket, $nonce, $timestamp, $url),
        ];
        return $sign;
    }

    /**
     * Sign the params.
     *
     * @param string $ticket
     * @param string $nonce
     * @param int $timestamp
     * @param string $url
     *
     * @return string
     */
    public function getSignature($ticket, $nonce, $timestamp, $url)
    {
        return sha1("jsapi_ticket={$ticket}&noncestr={$nonce}&timestamp={$timestamp}&url={$url}");
    }


//	public function sendTemp($openid,$data){
//		$access_token = $this->get_access_token();
//		$url ='https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token='.$access_token;
//		$tempid = $data['tempid'];
//		unset($data['tempid']);
// 		$template=array(
//			'touser'=>$openid,
//			'template_id'=>$tempid,    //模板的id
//			'data'=>$data
//		);
//
//		switch ($data['name']){
//			case 31://任务处理通知
//				$template['data']["first"]=["value"=>"您有新客户，请及时查看！", "color"=>"#173177"];
//				break;
//			case 32://关注成功通知
//				$template['data']["first"]=["value"=>_CONF('company')."欢迎您！", "color"=>"#173177"];
//				break;
//			case 34://订单支付成功通知
//
//				$template['data']["first"]=["value"=>"订单:".$data['order_id']."支付成功！", "color"=>"#173177"];
//				$data['order_id'];
//				$order = $this->StoreOrder->read_by_index($data['order_id']);
//				$template['data']["keyword1"]=["value"=>$data['order_id'], "color"=>"#FF0000"];
//				$template['data']["keyword2"]=["value"=>dc_scale($data['order_money']), "color"=>"#FF0000"];
//				break;
//		}
//		empty($template['data']["remark"]) && $template['data']["remark"]=["value"=>_CONF('company')."欢迎您！", "color"=>"#173177"];
//		$result = https_post($url,urldecode(xn_json_encode($template)));
//		$result = xn_json_decode($result);
//        if(!empty($result['errcode']) && $result['errcode']==40001){
//            $this->CacheDel('wx:access');
//            $this->sendTemp($data);
//        }
//	}

    //获取微信二维码--这玩意一般不需要吧--直接网址二维码就好了
    public function qrcode($user)
    {
        if (empty($user['uid'])) {
            return false;
        }
        $access_token = $this->get_access_token();
        $url = $this->api_host . 'cgi-bin/qrcode/create?access_token=' . $access_token;
        //echo '{"expire_seconds": 2592000, "action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": '.$user['uid'].'}}}}';
        $json = https_post($url, '{"expire_seconds": 2592000, "action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": ' . $user['uid'] . '}}}}');
        $json = xn_json_decode($json);
        !empty($json['errcode']) and xn_log($json['errmsg'], 'wxerror');
        if (!empty($result['errcode']) && $result['errcode'] == 40001) {
            $this->CacheDel('wx:access');
            $this->qrcode($user);
        }
        return $json;
    }


    public function get_user($openid)
    {
        if (empty($openid)) {
            return false;
        }
        $access_token = $this->get_access_token();
        $url = $this->api_host . 'cgi-bin/user/info?access_token=' . $access_token . '&openid=' . $openid . '&lang=zh_CN';
        $json = https_get($url);
        $json = xn_json_decode($json);
        !empty($json['errcode']) and xn_log($json['errmsg'], 'wxerror');
        if (!empty($json['errcode']) && $json['errcode'] == 40001) {
            return $this->get_user($openid);
        }
        return $json;
    }

    public function send_msg($openid, $message)
    {
        if (empty($openid)) {
            return '';
        }
        $access_token = $this->get_access_token();
        $msg = '{"touser": "' . $openid . '","msgtype": "text","text":{"content": "' . $message . '"}}';
        $rt = https_post($this->api_host . 'cgi-bin/message/custom/send?access_token=' . $access_token, $msg);
        $json = xn_json_decode($rt);
        !empty($json['errcode']) and xn_log($json['errmsg'], 'wxerror');
        if (!empty($json['errcode']) && $json['errcode'] == 40001) {
            $this->CacheDel('wx:access');
            return $this->send_msg($openid, $message);
        }
        return $json;
    }

    public function sendTemp($openid, $template_id, $data, $httpurl = '')
    {
        $access_token = $this->get_access_token();
        $url = $this->api_host . 'cgi-bin/message/template/send?access_token=' . $access_token;
        $_data = $data;
        $template = array(
            'touser' => $openid,
            'template_id' => $template_id,    //模板的id
            'data' => $data
        );
        $httpurl && $template['url'] = $httpurl;
        empty($template['data']["remark"]['value']) && $template['data']["remark"] = ["value" => _CONF('company') . "欢迎您！", "color" => "#173177"];
        $result = https_post($url, urldecode(xn_json_encode($template)));
        $_result = xn_json_decode($result);
        if (!empty($_result['errcode']) && $_result['errcode'] == 40001) {
            $this->CacheDel('wx:access');
            $this->sendTemp($openid, $template_id, $_data, $httpurl);
        } else {
            xn_log($openid . ' ' . $template_id . ' ' . $result, 'message');
        }
    }

    public function api_add_template($template_id_short)
    {
        if (empty($template_id_short)) {
            return '';
        }
        $access_token = $this->get_access_token();
        $msg = '{"template_id_short": "' . $template_id_short . '"}';
        $rt = https_post($this->api_host . 'cgi-bin/template/api_add_template?access_token=' . $access_token, $msg);
        $json = xn_json_decode($rt);
        !empty($json['errcode']) and xn_log($json['errmsg'], 'wxerror');
        if (!empty($json['errcode']) && $json['errcode'] == 40001) {
            $this->CacheDel('wx:access');
            return $this->api_add_template($template_id_short);
        }
        return $json;
    }


    //获取公众号粉丝openid列表一次1上限万个
    public function user_get($openid = '')
    {
        $access_token = $this->get_access_token();
        $url = $this->api_host . 'cgi-bin/user/get?access_token=' . $access_token . ($openid ? '&next_openid=' . $openid : '');
        $json = https_get($url);
        $json = xn_json_decode($json);
        !empty($json['errcode']) and xn_log($json['errmsg'], 'wxerror');
        if (!empty($json['errcode']) && $json['errcode'] == 40001) {
            $this->CacheDel('wx:access');
            return $this->user_get($openid);
        }
        return $json;
    }

    public function users_info($openids)
    {
        $access_token = $this->get_access_token();
        // https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}&lang=zh_CN
        $url = $this->api_host . 'cgi-bin/user/info/batchget?access_token=' . $access_token;
        $user_list = [];
        foreach ($openids as $openid) {
            $user_list[] = ['openid' => $openid];
        }
        $json = https_post($url, xn_json_encode(['user_list' => $user_list]));
        $json = xn_json_decode($json);
        !empty($json['errcode']) and xn_log($json['errmsg'], 'wxerror');
        if (!empty($json['errcode']) && $json['errcode'] == 40001) {
            $this->CacheDel('wx:access');
            return $this->users_info($openids);
        }
        return $json;
    }


    public function media_add($type, $media)
    {


    }

    public function media_get($MEDIA_ID)
    {


    }


    public function material_add()
    {


    }

    public function material_get($MEDIA_ID)
    {

    }

    public function material_batchget()
    {

    }

    public function material_del()
    {


    }

    public function material_update()
    {

    }


    //创建微信菜单
    public function create_menu($data)
    {
        $access_token = $this->get_access_token();
        $url = $this->api_host . 'cgi-bin/menu/create?access_token=' . $access_token;
        $json = https_post($url, $data);
        $json = xn_json_decode($json);
        if (!empty($json['errcode']) && $json['errcode'] == 40001) {
            $this->CacheDel('wx:access');
            return $this->create_menu($data);
        }
        $json['errcode'] != 0 and xn_log($json['errmsg'], 'wxerror');
        return $json;
    }

    //获取菜单
    public function get_menu()
    {
        $access_token = $this->get_access_token();
        $json = https_get($this->api_host . 'cgi-bin/menu/delete?access_token=' . $access_token);
        $json = xn_json_decode($json);
        if (!empty($json['errcode']) && $json['errcode'] == 40001) {
            $this->CacheDel('wx:access');
            return $this->get_menu();
        }
        $json['errcode'] != 0 and xn_log($json['errmsg'], 'wxerror');
        return $json;
    }


    public function responseMsg($postStr)
    {
        // hook model_wechatsdk_responseMsg_start.php

        $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_COMPACT | LIBXML_NOCDATA | LIBXML_NOBLANKS);
        $RX_TYPE = trim($postObj->MsgType);
        //消息类型分离

        $chat = $this->CacheGet('openid:' . $postObj->FromUserName);
        $this->CacheSet('openid:' . $postObj->FromUserName, $chat ? $chat : 0, 3600);

        switch ($RX_TYPE) {
            // hook model_wechatsdk_responseMsg_switch_start.php
            case 'event':
                // hook model_wechatsdk_responseMsg_switch_event_start.php

                if ($postObj->Event == 'LOCATION') {
                    $this->UserOpen->update(['openid' => $postObj->FromUserName, 'typeid' => 11], ['precision' => $postObj->Precision * 100000, 'latitude' => $postObj->Latitude * 100000, 'longitude' => $postObj->Longitude * 100000]);
                    return '';
                } else {
                    return $this->receiveEvent($postObj);
                }
            case 'text':
                // hook model_wechatsdk_responseMsg_switch_text_start.php
                //$postObj->Store = trim($postObj->Store);
                $content = trim($postObj->Content);
                if ($content == '我的信息') {
                    $data = [];
                    $data['typeid'] = 'text';
                    $data['content'] = $this->userinfo($postObj);
                } else {
                    if (isset($this->WechatKeys->data_array[$content])) {
                        $data = $this->WechatKeys->data_array[$content];
                    } else {
                        $arr = [];
                        foreach ($this->WechatKeys->data_array_mh as $k => $v) {
                            if (strpos($k, $content) !== false) {
                                $arr[] = $v;
                            }
                        }
                        $data = !empty($arr) ? $arr[array_rand($arr)] : [];
                    }
                    if ($chat) {
                        $data['typeid'] = 'customservice';
                    } else {
                        empty($data) && $data = $this->WechatKeys->data_array['default'];
                    }

                    if (!empty($data) && $data['typeid'] == 'customservice') {
                        $user = $this->UserOpen->read(['openid' => $postObj->FromUserName, 'typeid' => 11]);
                        if (!empty($user['uid'])) {
                            $user = $this->User->read_by_index($user['uid']);
                            $data = [
                                'cmd' => 'wechat', 'type' => 'text', 'id' => $user['uid'], 'username' => $user['nickname'], 'avatar' => $user['avatar'], 'message' => $content
                            ];
                        } else {
                            $user = $this->User->read_by_openid($postObj->FromUserName, 11);
                            $data = [
                                'cmd' => 'wechat', 'type' => 'text', 'id' => $postObj->FromUserName, 'username' => $user['nickname'], 'avatar' => $user['avatar'], 'message' => $content
                            ];
                        }
                        $this->CacheSet('openid:' . $postObj->FromUserName, 'chat', 3600);
                        $this->event->sendToGroup(2, xn_json_encode($data));
                        return '';
                    }
                    if (empty($data)) {
                        return false;
                    }
                }
                return $this->receive($postObj, $data);
            case 'image':
                // hook model_wechatsdk_responseMsg_switch_image_start.php
                return $this->transmitText($postObj, "好的图片已受到");
            case 'voice':
                // hook model_wechatsdk_responseMsg_switch_voice_start.php
                if (!empty($postObj->Recognition)) {
                    if (rtrim($postObj->Recognition, '。 ') == '我的信息') {
                        $content = $this->userinfo($postObj);
                    } else {
                        $user = $this->User->read_by_openid($postObj->FromUserName);
                        //PS 此处可以完成各种语音操作功能，比如 我的余额，我的业绩 ====
                        $reboot = \TianApi::robot($postObj->Recognition, !empty($user['uid']) ? $user['uid'] : 0);
                        if (!empty($reboot[0]['reply'])) {
                            $content = $reboot[0]['reply'];
                        } else {
                            $content = $postObj->Recognition;
                        }
                    }
                    return $this->transmitText($postObj, $content);
                } else {
                    return $this->transmitText($postObj, 'viceo');
                }
            case 'video':
                // hook model_wechatsdk_responseMsg_switch_voice_start.php
                return $this->transmitText($postObj, "好的[视频]已收到");
            case 'location':
                // hook model_wechatsdk_responseMsg_switch_location_start.php
                return $this->transmitText($postObj, "好的[位置]已收到");
            case 'link':
                // hook model_wechatsdk_responseMsg_switch_link_start.php
                return $this->transmitText($postObj, "好的[链接]已收到");
            case 'file':
                // hook model_wechatsdk_responseMsg_switch_file_start.php
                return $this->transmitText($postObj, "好的[文件]已收到");
            default:
                // hook model_wechatsdk_responseMsg_switch_default_start.php
                $data = $this->WechatKeys->data_array['default'];
                return $this->receive($postObj, $data);
        }
    }

    private function receive($object, $data)
    {
        switch ($data['typeid']) {
            case 'text':
                return $this->transmitText($object, $data['content']);
            case 'news':
                return $this->transmitNews($object, $data);
            case 'image':
                return $this->transmitImage($object, $data);
            case 'music':
                return $this->transmitMusic($object, $data);
            case 'video':
                return $this->transmitVideo($object, $data);
            case 'voice':
                return $this->transmitVoice($object, $data);
            case 'customservice':
                return $this->transmitText($object, $data['content']);
        }
    }

    //接收事件消息
    private function receiveEvent($postObj)
    {
        $postObj->FromUserName = trim($postObj->FromUserName);
        switch (trim($postObj->Event)) {
            case 'subscribe':
                // hook model_wechatsdk_responseMsg_switch_event_subscribe_start.php
                $open = $this->UserOpen->read(['openid' => $postObj->FromUserName, 'typeid' => 11]);
                $EventKey = str_replace('qrscene_', '', trim($postObj->EventKey));
                $updata = ['is_subscribe' => 1];
                if (is_numeric($EventKey)) {
                    if (empty($open['id'])) {
                        $open['id'] = $this->UserOpen->insertGetId(['openid' => $postObj->FromUserName, 'is_subscribe' => 1, 'typeid' => 11]);
                    }
                    if (empty($open['uid'])) {
                        $password = mt_rand(10000000, 99999999);
                        $salt = mt_rand(100000, 999999);
                        $newpwd = md5(md5($password) . $salt);
                        $_user = [
                            'username' => unid(),
                            'nickname' => "游客",
                            'password' => $newpwd,
                            'salt' => $salt,
                            'level_id' => $this->UserLevel->is_default,
                            'gid' => 10001,
                            'parent_uid' => $EventKey,
                            'create_ymd' => date('Ymd')
                        ];
                        $user['uid'] = $this->User->insert($_user);
                        $updata['uid'] = $user['uid'];
                    }
                }
	           !empty( $open['id']) && $this->UserOpen->update(['id' => $open['id']], $updata);
                $data = $this->WechatKeys->data_array['subscribe'];
                return $this->receive($postObj, $data);
            case 'unsubscribe'://取消关注
                // hook model_wechatsdk_responseMsg_switch_event_subscribe_start.php
                $this->UserOpen->update(['openid' => $postObj->FromUserName, 'typeid' => 11], ['is_subscribe' => 0]);
                return '';
            case 'CLICK':
                // hook model_wechatsdk_responseMsg_switch_event_click_start.php
                $EventKey = trim($postObj->EventKey);
                if ($EventKey == '我的信息') {
                    $data = [];
                    $data['typeid'] = 'text';
                    $data['content'] = $this->userinfo($postObj);
                } else {
                    $data = isset($this->WechatKeys->data_array[$EventKey]) ? $this->WechatKeys->data_array[$EventKey] : $this->WechatKeys->data_array['default'];
                }
                return $this->receive($postObj, $data);
//				switch ( $EventKey ) {
//
//					// hook model_wechatsdk_responseMsg_switch_event_click_switch_start.php
////					case "sign" :
////						$open_user = $this->User->read_by_openid($postObj->FromUserName);
////						$content = !empty($open_user['nickname'])?$open_user['nickname']:'欢迎归来！';
////						return $this->transmitText($postObj,$content);
////						break;
//					default :
//						$content = "即将呈现!";
//						return $this->transmitText($postObj,$content);
//						break;
//				}
            case "scancode_waitmsg":
                //http://www.qzrhbkj.com/app/index.php?i=2&c=entry&m=ewei_shopv2&do=mobile&r=diypage&id=
                $content = trim($postObj->ScanCodeInfo->ScanResult);
                return $this->transmitText($postObj, '扫码:' . $content);
            case "scancode_push" :
                $content = trim($postObj->ScanCodeInfo->ScanResult);
                return $this->transmitText($postObj, '扫码' . $content);
            case "SCAN" :
                // hook model_wechatsdk_responseMsg_switch_event_scan_start.php

                return $this->transmitText($postObj, $content);
            case "VIEW" :
                // hook model_wechatsdk_responseMsg_switch_event_view_start.php
                $content = "跳转链接 " . $postObj->EventKey;
                return $this->transmitText($postObj, $content);
            default:
                // hook model_wechatsdk_responseMsg_switch_event_default_start.php
                return $this->transmitText($postObj, '有什么可以帮您！');
        }
    }

    //回复文本消息
    private function transmitText($object, $content)
    {
        if (empty($content)) {
            return false;
        }
        $time = time();
        $xmlTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[text]]></MsgType>
                    <Store><![CDATA[%s]]></Store>
                </xml>";
        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, $time, $content);

        return $result;
    }

    //回复图片消息
    private function transmitImage($object, $data)
    {

        if (empty($data['image_url'])) {
            return false;
        }
        $time = time();
        $xmlTpl = "<xml>
					  <ToUserName><![CDATA[%s]]></ToUserName>
					  <FromUserName><![CDATA[%s]]></FromUserName>
					  <CreateTime>%s</CreateTime>
					  <MsgType><![CDATA[image]]></MsgType>
					  <Image>
						<MediaId><![CDATA[%s]]></MediaId>
					  </Image>
					</xml>";
        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, $time, $data['image_url']);
        //var_dump($result);
        return $result;
    }


    //回复视频消息
    private function transmitVideo($object, $data)
    {
        if (empty($data['video_url'])) {
            return false;
        }
        $time = time();
        $xmlTpl = "<xml>
				  <ToUserName><![CDATA[%s]]></ToUserName>
				  <FromUserName><![CDATA[%s]]></FromUserName>
				  <CreateTime>%s</CreateTime>
				  <MsgType><![CDATA[video]]></MsgType>
				  <Video>
					<MediaId><![CDATA[%s]]></MediaId>
					<Title><![CDATA[%s]]></Title>
					<Description><![CDATA[%s]]></Description>
				  </Video>
				</xml>";
        return sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, $time, $data['video_url'], $data['video_title'], $data['video_desc']);
    }


    //回复语音消息
    private function transmitVoice($object, $data)
    {

        if (empty($data['voice_url'])) {
            return false;
        }
        $time = time();
        $xmlTpl = "<xml>
				  <ToUserName><![CDATA[%s]]></ToUserName>
				  <FromUserName><![CDATA[%s]]></FromUserName>
				  <CreateTime>%s</CreateTime>
				  <MsgType><![CDATA[voice]]></MsgType>
				  <Voice>
					<MediaId><![CDATA[%s]]></MediaId>
				  </Voice>
				</xml>";
        return sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, $time, $data['voice_url']);
    }


    //回复音乐消息
    private function transmitMusic($object, $data)
    {
        if (empty($data['music_title'])) {
            return false;
        }
        $time = time();
        $xmlTpl = "<xml>
				  <ToUserName><![CDATA[%s]]></ToUserName>
				  <FromUserName><![CDATA[%s]]></FromUserName>
				  <CreateTime>%s</CreateTime>
				  <MsgType><![CDATA[music]]></MsgType>
				  <Music>
					<Title><![CDATA[%s]]></Title>
					<Description><![CDATA[%s]]></Description>
					<MusicUrl><![CDATA[%s]]></MusicUrl>
					<ThumbMediaId><![CDATA[%s]]></ThumbMediaId>
				  </Music>
				</xml>";
        return sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, $time, $data['music_title'], $data['music_desc'], $data['music_url'], $data['music_image']);
    }

    //回复图文消息
    private function transmitNews($object, $newsArray)
    {
        if (empty($newsArray)) {
            return false;
        }
        $itemTpl = "<item>
                    <Title><![CDATA[%s]]></Title>
                    <Description><![CDATA[%s]]></Description>
                    <PicUrl><![CDATA[%s]]></PicUrl>
                    <Url><![CDATA[%s]]></Url>
                </item>";
        $item_str = "";
        foreach ($newsArray as $item) {
            if(isset($item['Title'])){
                $item_str .= sprintf($itemTpl, $item['Title'], $item['Description'], $item['PicUrl'], $item['Url']);
            }
        }
        $time = time();
        $xmlTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[news]]></MsgType>
                    <ArticleCount>%s</ArticleCount>
                    <Articles>$item_str</Articles>
                </xml>";
        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, $time, count($newsArray));
        return $result;
    }

    // hook model_wechatsdk_end.php

}

?>